import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_crop/image_crop.dart';

class ImgCropPage extends StatefulWidget {
  final File sample;

  const ImgCropPage({Key key, this.sample}) : super(key: key);

  @override
  _ImgCropPageState createState() => _ImgCropPageState();
}

class _ImgCropPageState extends State<ImgCropPage> {
  final cropKey = GlobalKey<CropState>();

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.black,
        height: ScreenUtil.screenHeight,
        child: Stack(
          children: [
            widget.sample == null
                ? Container(
                    height: 10,
                    color: Colors.white,
                  )
                : Crop.file(widget.sample, key: cropKey),
            Align(
              alignment: Alignment.bottomCenter,
              child: FlatButton(
                child: Text(
                  'Crop Image',
                  style: Theme.of(context).textTheme.button.copyWith(color: Colors.white),
                ),
                onPressed: () => _cropImg(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // already choose cropped position. create final cropped img.
  Future<void> _cropImg() async {
    File file = widget.sample;
    final scale = cropKey.currentState.scale;
    final area = cropKey.currentState.area;
    if (area == null) {
      // cannot crop, widget is not setup
      debugPrint('cannot crop, widget is not setup');
      return;
    }
    final sample = await ImageCrop.sampleImage(
      file: file,
      preferredSize: (2000 / scale).round(),
    );

    final croppedFile = await ImageCrop.cropImage(
      file: sample,
      area: area,
    );
    sample?.delete();
    debugPrint('$croppedFile');
    _showCroppedImg(croppedFile);
  }

  void _showCroppedImg(File croppedFile) {
    showDialog(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return AlertDialog(
            content: Container(padding: EdgeInsets.all(10), child: Image.file(croppedFile)),
          );
        });
  }
}
